import axios from "axios";
// import qs from 'qs'
import { getToken } from "./store";
import { message } from "ant-design-vue";

var instance=axios.create({
  baseURL : "http://106.14.139.101:8080",
  // baseURL : "http://81.69.185.190:8082/pro_api",
  // baseURL : "http://81.69.185.190:8082",
  headers:{
    "Content-Type":"application/json"
  }
})

instance.interceptors.request.use(
  (config) => {
    if (config.method.toLocaleUpperCase() == "POST") {
      // config.data = qs.stringify(config.data)
    }
    // config.headers["Content-type"] = "application/json;charset=UTF-8"
    const token = getToken();
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// axios整体配置，对响应进行拦截
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error && error.response) {
      console.log("error.response.data:",error.response.data)
      message.error(error.response.data.error);
    } else {
      message.error('连接服务器失败！')
    }
    return Promise.reject(error)
  }
);

function postCPG(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance.post(url, params).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        console.log("postCPG():",error)
        reject(error);
      }
    );
  });
}

function getCPG(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance.get(url, { params }).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function downLoadFileCPG(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance.get(url, { params, responseType: "arraybuffer" }).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function uploadFileCPG(url, params = {}) {
  return new Promise((resolve, reject) => {
    axios.post(url, params).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function putCPG(url, params = {}) {
  return new Promise((resolve, reject) => {
    instance.put(url, params).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

function deletefnCPG(url, params) {
  return new Promise((resolve, reject) => {
    instance({
      method: "delete",
      url: url,
      params: params,
      data: params,
    }).then(
      (res) => {
        resolve(res.data);
      },
      (error) => {
        reject(error);
      }
    );
  });
}

export { getCPG, postCPG, downLoadFileCPG, deletefnCPG, uploadFileCPG,putCPG };
